const path = require('path');
const fsPromise = require('fs-promise');
const colors = require('colors-console');
const sleep = require('../lib/sleep.js');
let configInit = false;

const defaultConfig = {
    'version': 'v2.1',
    'clientServerPort': 3000,
    'manageServerPort': 3001,
    'clientCORS': true,
    'wwwPath': 'www',
    'prefixHTTPList': [],
    'CacheSave': {
        'state': true,
        // 缓存到文件
        'CacheSaveFile': true,
        // 缓存到数据库
        'CacheSaveDB': false
    },
    // v2.1版 试用令牌 2023-03-01 ~ 2023-06-01
    'WinUIAuth': '838731b582aa20d5e3f424af13068fc7fff39f63719ac254642865e57a958075807f139a258c123c97701a814e2371314c3adeb9587594d543e8fecf8955d0296023df88af7e75f185658b0a05dad290c9739ad29ba0fb492a50b7e471115187bda0532ddb1610adbbf9d85fcc0ff09684733b41088a3fac52a078becb9243ff8beb2a27e972bb56ce582d8bee61b8c2e7a1b7f9edd5b9fa95646172d0abfe12c17284c787cf75ff0d988c4380543b1c4035bf7b61d0a3392177bb936cf23ff9add756663c1205ae21f742d680846894ed2fe8a343ce5ba49dbd0c974edc85baed50e205f4a44edec6ffca777a505f4ef7851a4b6d38fc0bb859c1b210b6e829d5359d32761df394c75f97f65a0bd0b94c0323774d0a29d7c484c985e385908c692781990bae514cad350c04d3978bd4f39a07e250dbeb1a1735c3a74ada44c7ea32890a409e99b9b2b2fc19ef74b6f6df8ff929a8b561024c253ba1195a88271484e36e91caa378a39d7be3d4c59ee74a2a453fb4b683eebdde23cb2c5d8c28b421683be5235645b26d030880e3f2799f99d3748034baa67975a53b45d2f1def38fa596535ed0bb58bb686b50e5389c6ad5a08f0290819b19aa2f382a4f6506ab480e838a491f3cf56b6c25c1c354ef26cf5ddb579b211c02f2a0900d4d08177360d945d68fbefb8ec6f90f7ae7721e17fcd536dce142398b8bb30acf1973fc'
};

const configTool = {
    appBasePath: '',
    wwwPath: '',
    config: {} as any,
    async editConfig(key: string, value: any) {
        await this.init();
        let result = false;
        if (typeof this.config[key] === typeof value) {
            this.config[key] = value;
            await fsPromise.writeJSON(path.join(this.appBasePath, '/conf/config.json'), this.config);
            result = true;
        }
        return result;
    },
    async init() {
        return new Promise(async (resolve, reject) => {
            if (!configInit) {
                configInit = true;

                // 是否处于开发环境
                let isDev = !__dirname.includes('snapshot');

                if (isDev) {
                    this.appBasePath = path.join(__dirname, '../../');
                } else {
                    this.appBasePath = path.dirname(process.execPath);
                }

                await fsPromise.ensureDir(path.join(this.appBasePath, '/conf'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileOut'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileDB'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/logs/http'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/www'));

                let configFile = path.join(this.appBasePath, '/conf/config.json');

                // 判断是读取配置文件
                await fsPromise.readJson(configFile).then((d: any) => {
                    if (d.version === defaultConfig.version) {
                        this.config = d;
                    } else {
                        console.log(colors('red', '----|||配置文件版本过低，重置配置文件|||----'));
                        throw new Error('配置文件版本不匹配');
                    }
                }).catch(() => {
                    // 新生成一份配置文件
                    this.config = defaultConfig;
                    fsPromise.writeJSON(configFile, this.config);
                });

                this.wwwPath = path.join(this.appBasePath, this.config.wwwPath);
            }

            while (!configInit) {
                await sleep(50);
            }
            resolve(true);
        });

    },
    preservableONDB() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveDB;
    },
    preservableONFile() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveFile;
    }
};


export = configTool;
